package com.file.parser;

import com.file.bo.ABC;
import com.file.bo.ABCTran;
import com.file.bo.ResponseData;
import com.file.constant.EfpConstants;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Slf4j
public class ABCExcelParser {

    public ResponseData<String> parseABCExcelToJson(String filePath) {
        log.info("parseABCExcelToJson started, filePath:{}", filePath);
        String json = null;

        try {
            ABC abc = parseABCExcel(filePath);
            json = JsonUtils.convertObjectToJson(abc);
        } catch (Exception e) {
            log.error("[OnError]parseABCExcelToJson failed, filePath:{}", filePath, e);
            return new ResponseData<String>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(), ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseABCExcelToJson completed, filePath:{}", filePath);
        return new ResponseData<String>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private ABC parseABCExcel(String filePath) {
        ABC abc = new ABC();
        try (FileInputStream fis = new FileInputStream(new File(filePath));
             HSSFWorkbook workbook = new HSSFWorkbook(fis)) {
            HSSFSheet sheet = workbook.getSheetAt(0);

            List<ABCTran> abcTrans = new ArrayList<>();
            for (int i = 0; i < sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (i == 1) {
                    // "账号：6228480128813807772  户名：黄晓明 起始日期：20210606  截止日期：20210906"
                    String stringCellValue = row.getCell(0).getStringCellValue();
                    log.info("parseABCExcel the second row: {}", stringCellValue);
                    String[] strArray = stringCellValue.split("\\s+");
                    for (int j = 0; j < strArray.length; j++) {
                        if (j == 0) {
                            String accountNumber = strArray[j].split(EfpConstants.CN_SEMICOLON)[1];  // 中文分号
                            if (StringUtils.isNotBlank(accountNumber))
                                abc.setAccountNumber(accountNumber.trim());
                        } else if (j == 1) {
                            String accountName = strArray[j].split(EfpConstants.CN_SEMICOLON)[1];
                            if (StringUtils.isNotBlank(accountName))
                                abc.setAccountName(accountName.trim());
                        } else if (j == 2) {
                            String startDate = strArray[j].split(EfpConstants.CN_SEMICOLON)[1];
                            if (StringUtils.isNotBlank(startDate))
                                abc.setStartDate(startDate.trim());
                        } else if (j == 3) {
                            String expirationDate = strArray[j].split(EfpConstants.CN_SEMICOLON)[1];
                            if (StringUtils.isNotBlank(expirationDate))
                                abc.setExpirationDate(expirationDate.trim());
                        }
                    }
                }

                if (i >= 3) {
                    ABCTran abcTran = new ABCTran();
                    abcTran.setTransactionDate(row.getCell(0).getStringCellValue());
                    abcTran.setTransactionTime(row.getCell(1).getStringCellValue());
                    abcTran.setTransactionAmount(row.getCell(2).getStringCellValue());
                    abcTran.setCurrentBalance(row.getCell(3).getStringCellValue());
                    abcTran.setCounterPartyAccountName(row.getCell(4).getStringCellValue());
                    abcTran.setCounterPartyAccountNumber(row.getCell(5).getStringCellValue());
                    abcTran.setTransactionBank(row.getCell(6).getStringCellValue());
                    abcTran.setTransactionChannel(row.getCell(7).getStringCellValue());
                    abcTran.setTransactionType(row.getCell(8).getStringCellValue());
                    abcTran.setTradingPlace(row.getCell(9).getStringCellValue());
                    abcTran.setTradingSummary(row.getCell(10).getStringCellValue());
                    abcTrans.add(abcTran);
                }
            }
            abc.setAbcTrans(abcTrans);
        } catch (Exception e) {
            log.error("[OnError]parseABCExcel failed", e);
            throw new RuntimeException(e);
        }

        return abc;
    }

    public static void main(String[] args) throws IOException {
        String pdfFilePath = "E:\\data\\file\\农行流水.xls";
        String jsonFilePath = "E:\\data\\file\\农行流水.json";
        File jsonFile = new File(jsonFilePath);

        ABCExcelParser abcExcelParser = new ABCExcelParser();
        ResponseData<String> responseData = abcExcelParser.parseABCExcelToJson(pdfFilePath);
        log.info(responseData.getData());
        FileUtils.write(jsonFile, responseData.getData(), EfpConstants.UTF_8);
        jsonFile.createNewFile();
    }

}
